package com.kf.common.mvi.view

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewbinding.ViewBinding
import com.blankj.utilcode.util.BarUtils
import com.kf.common.mvi.viewmodel.BaseViewModel
import kotlinx.coroutines.launch

abstract class BaseActivity<V : ViewBinding, VM : BaseViewModel<*, *>> : AppCompatActivity() {

    val TAG = "HXW"
    protected lateinit var mView: V
    protected lateinit var mViewModel: VM
    protected val inflater: LayoutInflater by lazy { LayoutInflater.from(this) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewModel = createViewModel()
        mView = createViewBind()
        setContentView(mView.root)
        initStateFlow()
        BarUtils.transparentStatusBar(this)
    }

    fun initStateFlow() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                mViewModel.mutableContainer.requestStateFlow.collect {
                    if (it.request) {
                        showDialog()
                    } else if (it.complate) {
                        hideDialog()
                    } else if (it.erro) {
                        showEmptyView()
                    }
                }
            }
        }
    }

    abstract fun createViewModel(): VM
    abstract fun createViewBind(): V

    //显示等待对话框
    fun showDialog(){
        log("showDialog")
    }
    //关闭等待对话框
    fun hideDialog(){
        log("hideDialog")
    }
    //显示错误界面
    fun showEmptyView(){
        log("showEmptyView")
    }

    fun log(msg : String){
        Log.e(TAG,msg)
    }

}